<?php
class Tools{
    static $length = 3;
    public static function setValue($key,$val){
        $redis = new \think\cache\driver\Redis(['length' => self::$length]);
        $redis->set($key, $val);
    }

    /**
     * XML文档转为数组
     * @param string $xml XML文档字符串
     * @return array
     */
    public static function xmlToArray($xml)
    {
        return $xml ? self::xmlToArrayElement(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)) : array();
    }

    /**
     * xml文档转为数组元素
     * @param obj $xmlobject XML文档对象
     * @return array
     */
    public static function xmlToArrayElement($xmlobject)
    {
        $data = array();
        foreach ((array)$xmlobject as $key => $value) {
            $data[$key] = !is_string($value) ? self::xmlToArrayElement($value) : $value;
        }
        return $data;
    }

    //根据生日计算年龄
    public static function calculateAge($birthdate) {
        // 将传入的生日字符串转换为DateTime对象
        $birthDate = new DateTime($birthdate);
        // 获取当前日期
        $today = new DateTime('now');
        // 计算两个日期之间的差异
        $age = $today->diff($birthDate);
        // 返回年龄
        return $age->y; // y代表年份，即年龄
    }
    public static function getValue($key){
        $redis = new \think\cache\driver\Redis(['length' => self::$length]);
        return $redis->get($key);
    }
    public static function getDistance($lng1, $lat1, $lng2, $lat2)
    {
        //lat   维度
        //lng   经度
        if (empty($lng1) || empty($lat1) || empty($lng2) || empty($lat2)) {
            return 99999;
        }
        $earthRadius = 6367000; //approximate radius of earth in meters

        /*
        Convert these degrees to radians
        to work with the formula
        */

        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        /*
        Using the
        Haversine formula

        http://en.wikipedia.org/wiki/Haversine_formula

        calculate the distance
        */

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude
                / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }
    //获取短名
    public static function getshortname($name){
        return mb_substr($name, 0, 1) . "*";
    }
     public static function checkArrayResult($arr)
    {
        if (!is_array($arr)) return false;
        foreach ($arr as $a) {
            if (!$a) return false;
        }
        return true;
    }
    /**
     * @param        $url
     * @param string $method
     * @param null $postFields
     * @param null $header
     *
     * @return mixed
     * @throws Exception
     */
    public static function curl($url, $method = 'GET', $postFields = null, $header = null, $cookie = null, $savecookie = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);

        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        switch ($method) {
            case 'POST':
                if (!empty($postFields)) {
                    if (is_array($postFields) || is_object($postFields)) {
                        if (is_object($postFields))
                            $postFields = Tools::object2array($postFields);
                        $postBodyString = "";
                        $postMultipart = false;
                        foreach ($postFields as $k => $v) {
                            if ("@" != substr($v, 0, 1) || in_array($k, array("name", "nick"))) { //判断是不是文件上传
                                $postBodyString .= "$k=" . urlencode($v) . "&";
                            } else { //文件上传用multipart/form-data，否则用www-form-urlencoded
                                $postMultipart = true;
                                if (class_exists("CURLFile")) {
                                    $postFields[$k] = new CURLFile(realpath(str_replace("@", "", $v)));
                                }
                            }
                        }
                        unset($k, $v);
                        if ($postMultipart) {
                            if (class_exists("CURLFile")) {
                                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
                            } else {
                                if (defined('CURLOPT_SAFE_UPLOAD')) {
                                    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
                                }
                            }
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                        } else {
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
                        }
                    } else {
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                    }
                }
                break;
            case 'PUT':
                if (!empty($postFields)) {
                    if (is_array($postFields) || is_object($postFields)) {
                        if (is_object($postFields))
                            $postFields = Tools::object2array($postFields);
                        $postBodyString = "";
                        $postMultipart = false;
                        foreach ($postFields as $k => $v) {
                            if ("@" != substr($v, 0, 1)) { //判断是不是文件上传
                                $postBodyString .= "$k=" . urlencode($v) . "&";
                            } else { //文件上传用multipart/form-data，否则用www-form-urlencoded
                                $postMultipart = true;
                                if (class_exists("CURLFile")) {
                                    $postFields[$k] = new CURLFile(realpath(str_replace("@", "", $v)));
                                }
                            }
                        }
                        unset($k, $v);
                        if ($postMultipart) {
                            if (class_exists("CURLFile")) {
                                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
                            } else {
                                if (defined('CURLOPT_SAFE_UPLOAD')) {
                                    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
                                }
                            }
                            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                            curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                        } else {
                            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                            curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
                        }
                    } else {
                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                    }

                }
                break;
            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
            case 'GET':
                if (!empty($postFields) && is_array($postFields))
                    $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($postFields);
                break;
            default:
                if (!empty($postFields) && is_array($postFields))
                    $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($postFields);
                break;
        }
        curl_setopt($ch, CURLOPT_URL, $url);

        if (!empty($header) && is_array($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        if (!empty($savecookie)) {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
        } else {
            if (!empty($cookie)) {
                curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); //读取cookie
            }
        }
        $response = curl_exec($ch);

//        \Common::setlog("jiexicurl", "登录经纬度逆解析失败：" . json_encode($response));
//        \Common::setlog("jiexicurl", "登录经纬度逆解析失败：" . $url);
        if (isset($_GET['debug']) && $_GET['debug'] == 1) {
            var_dump(curl_error($ch));
            $aStatus = curl_getinfo($ch);
            var_dump($aStatus);
        }
//        var_dump(curl_errno($ch));
        if (curl_errno($ch)) {
            //throw new Exception(curl_error($ch), 0);
        }
        curl_close($ch);

        return $response;
    }

    public static function object2array(&$object)
    {
        return json_decode(json_encode($object), true);
    }
    public static function getaccessToken(){
        // 配置参数
        $AppModel = new \app\admin\model\vppz\App();
        $app = $AppModel->find(1);
        $appid = $app['wxapp_id'];
        $secret = $app['wxapp_secret'];
        $object = new \Wxchat($appid, $secret);
        $accessToken = $object->getaccesstoken();
        return $accessToken;
    }
/**
     * 生成宣传海报
     * @param array  参数,包括图片和文字
     * @param string $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
     * @return [type] [description]
     */
    public static function createPoster($config = array(), $filename = "")
    {
        //如果要看报什么错，可以先注释调这个header
        if (empty($filename)) header("content-type: image/png");
        $imageDefault = array(
            'left' => 0,
            'top' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 1000,
            'height' => 1000,
            'opacity' => 100
        );
//        $textDefault = array(
//            'text'=>'啊啊啊',
//            'left'=>0,
//            'top'=>0,
//            'fontSize'=>32,       //字号
//            'fontColor'=>'0,0,0', //字体颜色
//            'angle'=>0,
//        );
//        $ttf = "../public/static/font/simhei.ttf";
        $background = $config['background'];//海报最底层得背景
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background);  //背景宽度
        $backgroundHeight = imagesy($background);  //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        // imageColorTransparent($imageRes, $color);  //颜色透明
        imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
        //处理了图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault, $val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                if ($val['stream']) {   //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
                //放置图像
                imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
//        if (!empty($config['text'])) {
//            foreach ($config['text'] as $key => $val) {
//                list($R, $G, $B) = explode(',', $val['fontColor']);
//                self::draw_txt_to($imageRes, array(
//                    'color' => array($R, $G, $B),
//                    'fontsize' => $val['fontSize'],
//                    'width' => $backgroundWidth - $val['left'] * 1.3,
//                    'left' => $val['left'],
//                    'top' => $val['top']
//                ), $ttf, $val['text']);
////                $val = array_merge($textDefault,$val);
////                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
////                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
////                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
////                if(isset($val['sub']) == 1){
////                    imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$ttf,$val['text']);
////                }else {
////                    imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $ttf, $val['text']);
////                    imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'] + 2, $val['top'], $fontColor, $ttf, $val['text']);
////                    imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'] + 3, $val['top'], $fontColor, $ttf, $val['text']);
////                }
//            }
//        }
        //生成图片
        if (!empty($filename)) {
            $res = imagejpeg($imageRes, $filename, 90); //保存到本地
            imagedestroy($imageRes);
            if (!$res) return false;
            return $filename;
        } else {
            imagejpeg($imageRes);     //在浏览器上显示
            imagedestroy($imageRes);
        }
    }

    public static function draw_txt_to($card, $pos, $font_file, $string)
    {

        $font_color = imagecolorallocate($card, $pos['color'][0], $pos['color'][1], $pos['color'][2]);
        $_string = '';
        $__string = '';

        for ($i = 0; $i < mb_strlen($string); $i++) {
            $box = imagettfbbox($pos['fontsize'], 0, $font_file, $_string);
            $_string_length = $box[2] - $box[0];
            $box = imagettfbbox($pos['fontsize'], 0, $font_file, mb_substr($string, $i, 1));

            if ($_string_length + $box[2] - $box[0] < $pos['width']) {
                $_string .= mb_substr($string, $i, 1);
            } else {
                $__string .= $_string . "\n";
                $_string = mb_substr($string, $i, 1);
            }
        }
        $__string .= $_string;
        $box = imagettfbbox($pos['fontsize'], 0, $font_file, mb_substr($__string, 0, 1));
        imagettftext(
            $card,
            $pos['fontsize'],
            0,
            $pos['left'],
            $pos['top'] + ($box[3] - $box[7]),
            $font_color,
            $font_file,
            $__string);
    }
    /**
     * 生成二维码
     */
    public static function qrcode($content, $path = false, $logo = '')
    {
        error_reporting(E_ERROR);
        require __DIR__ . '/../thinkphp/library/think/Phpqrcode/phpqrcode.php';
        $url = urldecode($content);
        if ($path) {
            //带图片二维码
            QRcode::png($url, $path);
            if ($logo !== FALSE) {
                $QR = imagecreatefromstring(file_get_contents(\Request::instance()->domain() . '/' . $path));
                $logo = imagecreatefromstring(file_get_contents($logo));
                $QR_width = imagesx($QR);
                $QR_height = imagesy($QR);
                $logo_width = imagesx($logo);
                $logo_height = imagesy($logo);
                $logo_qr_width = $QR_width / 5;
                $scale = $logo_width / $logo_qr_width;
                $logo_qr_height = $logo_height / $scale;
                $from_width = ($QR_width - $logo_qr_width) / 2;
                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            }
            $path_name = substr($path, 0, strpos($path, '.'));
            unlink($path);
            imagepng($QR, 'upload/spark/schoolexam/' . $path_name . 'png');//带Logo二维码的文件名
        } else {
            return QRcode::png($url, $path);
        }
    }
    public static function generateShortUniqueId() {
        // 获取微秒级时间戳，确保唯一性基础
        $timestamp = microtime(true) * 10000;

        // 生成随机数增加唯一性
        $random = mt_rand(100000, 999999);

        // 组合并进行哈希处理
        $data = $timestamp . $random . mt_rand();
        $hash = hash('sha256', $data);

        // 截取前16-20个字符（根据需要调整长度）
        $shortId = substr($hash, 0, 20);

        return $shortId;
    }
}
